<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Search extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
		$this->load->database();
		$this->load->helper('form');
		$this->load->helper('url');
		show_404('', FALSE);
    }

	public function index()
	{
		$this->load->view('header');
		$this->load->view('search_input');
		$this->load->view('footer');
	}

	public function find()
	{
		$key = $this->input->post('key');
		if($key == ''){
			$data['error'] = "Keywords can't be empty";
		}
		else{
			$query = 'SELECT * FROM question WHERE title LIKE "%'.$key.'%"';
			$result = $this->getDbResult($query);
			if(empty($result)){
				$data['error'] = "Don't find anything. Change keywords, Please.";
			}
			else{
				$data['result'] = $result;
			}
			$data['key'] = $key;
		}

		$this->load->view('header');
		$this->load->view('search_input', $data);
		$this->load->view('search_result', $data);
		$this->load->view('footer');
	}

	public function type($type = '0'){
		$data['href'][0] = 'search/type/0';
		$data['href'][1] = 'search/type/1';
		$data['href'][2] = 'search/type/2';

		if ($type == '0'){
			$query = 'SELECT * FROM question WHERE type = "单选"';
		}
		elseif ($type == '1') {
			$query = 'SELECT * FROM question WHERE type = "多选"';
		}
		elseif ($type == '2') {
			$query = 'SELECT * FROM question WHERE type = "判断"';
		}
		$data['href'][$type] = '#';
		$data['result'] = $this->getDbResult($query);

		$this->load->view('header');
		$this->load->view('search_input');
		$this->load->view('search_type', $data);
		$this->load->view('search_result', $data);
		$this->load->view('footer');
	}

	private function getDbResult($query){
		$result = $this->db->query($query);
		$find_result = array();
		foreach ($result->result_array() as $row)
		{
			$find_result[] = $row;
		}
		return $find_result;
	}
}